package com.mikgonz.farkle.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.IntentAction;
import com.mikgonz.farkle.LocalGameController;
import com.mikgonz.farkle.Player;
import com.mikgonz.farkle.R;
import com.mikgonz.farkle.Util;

public class GameScreen extends Activity implements AnimationEndListener {

	// UI Elements
	private Resources r;
	private Button scoreButton;
	private Button rollButton;
	private LocalGameController controller;

	// Convenience Arrays
	private ArrayList<MyImageView> imageViews = new ArrayList<MyImageView>();
	private int[] letters = new int[6];
	private ArrayList<TableRow> rows = new ArrayList<TableRow>();

	// Need this for a delay
	public Handler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.game_screen);
		r = getResources();
		initializeArrays();
		scoreButton = (Button) findViewById(R.id.score_button);
		rollButton = (Button) findViewById(R.id.roll_button);
		setupActionBar();
		handler = new Handler();

		// Restore GameController
		restoreGameController();
		// Restore UI elements
		restoreState(savedInstanceState);
	}

	private void setupActionBar() {
		ActionBar bar = (ActionBar) findViewById(R.id.actionbar);

		Intent restart = new Intent(this, Main.class);
		restart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TOP);
		bar.setHomeAction(new IntentAction(this, restart, R.drawable.house));

	}

	private void restoreState(Bundle savedInstanceState) {

		if (savedInstanceState != null
				&& savedInstanceState.getBoolean("hasState")) {

			scoreButton.setEnabled(savedInstanceState.getBoolean("scoreState"));
			rollButton.setEnabled(savedInstanceState.getBoolean("rollState"));
		}
	}

	private void restoreGameController() {

		if (getLastNonConfigurationInstance() != null) {
			controller = (LocalGameController) getLastNonConfigurationInstance();
			controller.newUI(this);
			updateImages();
		} else {
			controller = new LocalGameController(this);
		}
	}

	// These arrays allows the use of a for loop in updateImages()
	private void initializeArrays() {

		imageViews.add((MyImageView) findViewById(R.id.img_1));
		imageViews.add((MyImageView) findViewById(R.id.img_2));
		imageViews.add((MyImageView) findViewById(R.id.img_3));
		imageViews.add((MyImageView) findViewById(R.id.img_4));
		imageViews.add((MyImageView) findViewById(R.id.img_5));
		imageViews.add((MyImageView) findViewById(R.id.img_6));

		rows.add((TableRow) findViewById(R.id.first_row));
		rows.add((TableRow) findViewById(R.id.second_row));
		rows.add((TableRow) findViewById(R.id.third_row));
		rows.add((TableRow) findViewById(R.id.fourth_row));

		letters[0] = R.drawable.f;
		letters[1] = R.drawable.a;
		letters[2] = R.drawable.r;
		letters[3] = R.drawable.k;
		letters[4] = R.drawable.l;
		letters[5] = R.drawable.e;

	}

	public void onRoll(View v) {

		controller.onRoll();
	}

	public void onScore(View v) {
		controller.onScore();
	}

	public void onClickDice(View v) {
		controller.onClickDice(Util.identifyView(v));
	}

	// Called from the GameController Object
	public void setRollButtonState(boolean state) {
		rollButton.setEnabled(state);
	}

	public boolean getRollButtonState() {
		return rollButton.isEnabled();
	}

	// Called from the GameController Object
	public void setScoreButtonState(boolean state) {
		scoreButton.setEnabled(state);
	}

	public boolean getScoreButtonState() {
		return scoreButton.isEnabled();
	}

	public void hideRows(int numOfPlayers) {
		for (TableRow r : rows) {
			final int index = rows.indexOf(r);
			if (index >= numOfPlayers)
				r.setVisibility(View.GONE);
		}
	}

	public void setPlayerName(int playerNum, String name, boolean isUp) {
		final TableRow row = rows.get(playerNum - 1);
		final TextView text = (TextView) row.findViewById(R.id.name_text);

		text.setText(name);
		if (isUp)
			text.setTypeface(Typeface.DEFAULT_BOLD);
		else
			text.setTypeface(Typeface.DEFAULT);
	}

	public void updatePlayerScore(int playerNum, String newScore) {
		final TableRow row = rows.get(playerNum - 1);
		final TextView text = (TextView) row.findViewById(R.id.score_text);

		text.setText(newScore);
	}

	public void updatePlayerTempScore(int playerNum, String newTempScore) {
		if (newTempScore == null)
			return;

		final TableRow row = rows.get(playerNum - 1);
		final TextView text = (TextView) row.findViewById(R.id.temp_score_text);

		text.setText(newTempScore);
	}

	public void updateFarkleImages(int playerNum, int numOfFarkles) {

		// final TableRow row = rows.get(playerNum - 1);
		// final ImageView image = (ImageView)
		// row.findViewById(R.id.farkle_image);

		// TODO Switch case here that will choose between the three drawables
		// final int id;
		// switch (numOfFarkles) {
		// case (1):
		// id = R.drawable.one_farkle;
		// break;
		// case (2):
		// id = R.drawable.two_farkle;
		// break;
		// case (3):
		// id = R.drawable.three_farkle;
		// break;
		// default:
		// id = -1;
		// break;
		// }
		// if(id != -1)
		// image.setImageDrawable(r.getDrawable(id));

	}

	public void updateImages() {

		MyImageView i = null;
		for (int j = 0; j < imageViews.size(); j++) {
			i = imageViews.get(j);
			i.setImageDrawable(r.getDrawable(controller.getImage(j)));
		}
	}

	public void animateImages() {

		Animation a = AnimationUtils.loadAnimation(this, R.anim.dice_animation);
		MyImageView i = null;

		for (int j = 0; j < imageViews.size(); j++) {

			i = imageViews.get(j);
			i.setImageDrawable(r.getDrawable(controller.getImage(j)));

			if (!controller.shouldAnimate(j))
				continue;

			i.setAnimationEndListerner(this);
			i.clearAnimation();
			i.startAnimation(a);

		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean("hasState", true);
		outState.putBoolean("scoreState", scoreButton.isEnabled());
		outState.putBoolean("rollState", rollButton.isEnabled());

		super.onSaveInstanceState(outState);
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return controller;
	}

	public void showFarkle() {

		rollButton.setEnabled(false);
		scoreButton.setEnabled(false);

		MyImageView i = null;
		for (int j = 0; j < imageViews.size(); j++) {

			Animation a = AnimationUtils.loadAnimation(GameScreen.this,
					R.anim.dice_animation);
			a.setStartOffset(j * 200);
			i = imageViews.get(j);
			
			if (j == 5)
				i.setAnimationEndListerner(this);
			else
				i.setAnimationEndListerner(null);

			i.setImageDrawable(r.getDrawable(letters[j]));
			i.clearAnimation();
			i.startAnimation(a);
		}

	}

	@Override
	public void onAnimationEnd(View v) {
		controller.onAnimationEnd(v);
	}

	public void alertOfWinner(Player winner) {
		setRollButtonState(false);
		setScoreButtonState(false);

		// TODO show Two buttons: Play Again, Exit

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(false);

		// TODO change these to strings from xml
		builder.setMessage("Congratulations to " + winner.getName()
				+ "! You have won!");

		// Tells the dialog what to do when the button is clicked
		builder.setNeutralButton("YAY!", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
				dialog.dismiss();
			}

		});
		// Create the dialog and show it
		builder.show();
	}
}
